package leetcodecompetition.D339;

import org.junit.jupiter.api.Test;
import tool.s;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class T6365 {
    int[] re;
    Set<Integer> set;

    public int[] minReverseOperations(int n, int p, int[] banned, int k) {
        re = new int[n];
        set = new HashSet<>();
        for (int i = 0; i < banned.length; i++) {
            set.add(banned[i]);
        }
        Arrays.fill(re, -2);
        for (int i = 0; i < n; i++) {
            Set<Integer> lujing = new HashSet<>();
            minReverseOperationsHelp(n, p, k, i, lujing);
        }
        return re;
    }

    public int minReverseOperationsHelp(int n, int p, int k, int d, Set<Integer> lujing) {
        if (d == p) return re[d] = 0;
        if (set.contains(d)) return re[d] = -1;
        int min = Integer.MAX_VALUE;
        int next;
        for (int i = k - 1; i > 0; i -= 2) {
            if (d + i >= 0 && d + i < n && !lujing.contains(d + i)) {
                lujing.add(d + i);
                next = minReverseOperationsHelp(n, p, k, d + i, lujing);
                lujing.remove(d + i);
                if (next != -1) min = Math.min(min, next);
            }
            if (d - i >= 0 && d - i < n && !lujing.contains(d - i)) {
                lujing.add(d - i);
                next = minReverseOperationsHelp(n, p, k, d - i, lujing);
                lujing.remove(d - i);
                if (next != -1) min = Math.min(min, next);
            }
        }
        if (min == Integer.MAX_VALUE) return re[d] = -1;
        re[d] = min + 1;
        return re[d];
    }

    @Test
    public void test() {
        int[] b = {};
        int[] r = minReverseOperations(5, 0, b, 2);
        s.print(r);
    }
}
